package com.cn.tous.security.controller;

import com.cn.tous.security.dtos.LoginParam;
import com.cn.tous.security.dtos.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author mengwei
 * @description AuthController
 * @createDate 2025/7/28 17:18
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthenticationManager authenticationManager;


    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginParam param) {
        Authentication authenticationRequest =
                UsernamePasswordAuthenticationToken.unauthenticated(param.getUsername(), param.getPassword());
        Authentication authenticationResponse =
                authenticationManager.authenticate(authenticationRequest);


        TestingAuthenticationToken testingAuthenticationToken =
                new TestingAuthenticationToken("username", "password", "ROLE_USER");

        SecurityContextHolder.getContext().setAuthentication(testingAuthenticationToken);

        // 可以添加用户信息到响应中
        UserDetails userDetails = (UserDetails) authenticationResponse.getPrincipal();

        return Result.success();
    }
}
